package com.cmc.cloud.cmclink.doc.rpcservice.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.cmc.cloud.cmclink.doc.api.document.emums.PayTypeEnum;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.ApiErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.rpcservice.AccountTransfer;
import com.cmc.cloud.cmclink.fin.api.DocBlnoApi;
import com.cmc.cloud.cmclink.fin.api.base.dto.req.DocBlnoBaseReqDTO;
import com.cmc.cloud.cmclink.fin.api.base.dto.req.DocBlnoChangeBaseReqDTO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.ex.Assertion;

import lombok.extern.slf4j.Slf4j;

/**
 * 运费发送业财实现类
 *
 * @author dev89
 * @date 2025/08/13 15:28
 **/
@Service
@Validated
@Slf4j
public class AccountTransferImpl implements AccountTransfer {
    private static final String GET_CNTR_TYPE_EXCEPTION = "freight计费发送财务失败";
    @Resource
    private DocBlnoApi docBlnoApi;

    @Override
    public boolean createBlnoFreight(DocBlnoBaseReqDTO docBlnoBaseReq) {
        return createBlnoPay(docBlnoBaseReq, PayTypeEnum.INCOME.getValue());
    }

    @Override
    public boolean createBlnoChangeFreight(DocBlnoChangeBaseReqDTO docBlnoChangeBaseReq) {
        CommonResult<Boolean> commonResult;
        try {
            commonResult = docBlnoApi.createBlNoChange(docBlnoChangeBaseReq);
        } catch (Exception e) {
            log.error(GET_CNTR_TYPE_EXCEPTION, e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.BLNO_FREIGHT_CHANGE_TO_ACCOUNT_EXCEPTION);
        }

        return commonResult.getCheckedData();
    }

    @Override
    public boolean createBlnoPay(DocBlnoBaseReqDTO docBlnoBaseReq, String payType) {
        CommonResult<Boolean> commonResult = new CommonResult<>();
        try {
            if (PayTypeEnum.COST.getValue().equals(payType)) {
                commonResult = docBlnoApi.createLocalBlNo(docBlnoBaseReq);
            } else {
                commonResult = docBlnoApi.createBlNo(docBlnoBaseReq);
            }
        } catch (Exception e) {
            log.error(GET_CNTR_TYPE_EXCEPTION, e);
            Assertion.assertTrue(false).raise0(ApiErrorCodeConstants.BLNO_FREIGHT_TO_ACCOUNT_EXCEPTION.getCode(),
                e.toString());
        }

        if (commonResult == null || commonResult.getData() == null) {
            log.error(GET_CNTR_TYPE_EXCEPTION);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.BLNO_FREIGHT_TO_ACCOUNT_NULL);
        }

        if (!commonResult.getData()) {
            log.error(GET_CNTR_TYPE_EXCEPTION + "{}", commonResult.getMsg());
            Assertion.assertTrue(false).raise0(ApiErrorCodeConstants.BLNO_TO_ACCOUNT_RETURN_FALSE.getCode(),
                commonResult.getMsg());
        }
        return commonResult.getCheckedData();
    }
}
